<!--
 * @Description: 登录
 * @Author: liu (1427179517@qq.com)
 * @Date: 2022-01-08 10:26:22
 * @LastEditors: liu (1427179517@qq.com)
 * @LastEditTime: 2023-05-09 09:05:30
 * @FilePath: \jiekuan-app\src\pages\login\login.vue
-->
<template>
  <div class="page" :class="isLogin ? 'page1' : 'page2'">
    <div class="page-header"></div>
    <div class="page-content u-p-0">
      <div class="box" v-if="isLogin">
        <div class="text">为单身男女打造的 <br />专业约会平台</div>
        <button class="btn u-m-t-78" @click="handleClickStop({ type: 'login' })">登录</button>
        <div class="u-flex u-col-center agreement u-m-t-55">
          <div @click="isagreement = !isagreement" class="u-m-r-22">
            <image src="../../static/images/round_null.png" class="icon" alt="" v-if="!isagreement" />
            <u-icon name="checkmark-circle" v-else color="#f6bf5d" size="32"></u-icon>
          </div>
          同意<text class="agreement_text">《用户协议》</text>和<text class="agreement_text">《隐私政策》</text
          >并同意授权
        </div>
      </div>
      <div v-else class="wxLogin">
        <u-form :model="form" ref="uForm" class="mobile-form" :label-width="0" :border-bottom="false">
          <u-form-item label="" class="mobile-form-item" prop="username " :border-bottom="false">
            <u-input
              type="number"
              maxlength="11"
              placeholder="请输入手机号码"
              class="mobile-form-item_input"
              v-model="form.username"
              focus
              :placeholder-style="placeholderStyle"
            />
          </u-form-item>
          <div class="u-flex u-row-between u-col-center sendcode" v-if="isCode">
            <span> 验证码已发送至您手机 </span>
            <span class="mobile-form-item_code-button u-flex u-row-center">
              {{ changeText }}
            </span>
          </div>
          <u-form-item label="" class="mobile-form-item code_box" prop="authCode " :border-bottom="false">
            <u-message-input
              class="flex-1"
              :breathe="false"
              font-size="63"
              :maxlength="6"
              @finish="handleFinish"
            ></u-message-input>
          </u-form-item>
          <div class="u-flex u-row-center">
            <!-- <span class="code_text" @click.stop="handleClickStop({ type: 'sendCode' })">{{ code_text }}</span> -->
            <button
              class="mobile-form-item_code-button code_text"
              @click.stop="handleClickStop({ type: 'sendCode' })"
              :disabled="isDisabled"
            >
              {{ code_text }}
            </button>
          </div>
          <u-form-item label="" :border-bottom="false">
            <u-button class="btn2" @click.stop="submitValidate" shape="circle"> 登录 </u-button>
          </u-form-item>
        </u-form>
      </div>
    </div>
    <!-- 仅为了获取验证码倒计时 -->
    <u-verification-code :seconds="seconds" ref="uCode" @change="codeChange" change-text="xs"></u-verification-code>
    <u-no-network></u-no-network>
    <div class="page-footer"></div>
  </div>
</template>

<script>
import { getAmapCode } from '@/utils/publicMethod'

import { vailData } from '@/utils/regular'
export default {
  name: '', // 页面名称
  components: {}, // 挂载组件
  props: {}, // 组件传值
  data() {
    return {
      form: {
        username: '',
        authCode: '',
        // platform: 0,
      },
      rules: {
        username: [
          { required: true, type: 'string', message: '请输入手机号', trigger: ['blur'] },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              this.mobileVerified = this.$u.test.mobile(value)
              return this.mobileVerified
            },
            message: '手机号码不正确',
            trigger: ['change', 'blur'],
          },
        ],
        authCode: [
          { max: 4, message: '请输入验证码', trigger: 'change' },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              this.codeVerified = value.length === 4
              return this.codeVerified
            },
            message: '验证码限4位',
            trigger: ['change', 'blur'],
          },
        ],
      },
      seconds: 60, // 倒计时时间
      changeText: '',
      isDisabled: false, // 禁用验证码
      mobileVerified: false, // 手机号通过
      codeVerified: false, // 验证码通过
      placeholderStyle: 'color: #c0c4cc;',
      isagreement: false, // 协议勾选
      isLogin: true, // 登录
      code_text: '获取验证码', // 验证码文字
      isCode: false, // 发送了验证码
    }
  },
  computed: {}, // 计算机属性 类似与data概念
  watch: {}, // 监控data中数据变化
  created() {}, // 生命周期-创建完成(可以访问当前this实例)
  mounted() {
      this.$store.commit('user/setToken', "")
      this.$store.commit('user/setTokenHead', "Bearer ")
  }, // 生命周期-挂载完成(可以访问DOM元素)
  methods: {
    // 验证码输入完成
    handleFinish(value) {
      this.form.authCode = value
    },
    // 获取用户机型
    getSystemInfo() {
      const that = this
      uni.getSystemInfo({
        success: (res) => {
          if (res.platform === 'ios') {
            that.form.platform = 1
          } else {
            that.form.platform = 2
          }
          // that.getNowLocation()
        },
      })
    },
    /**
     * @author: yilingsj（315800015@qq.com）
     * @description: 倒计时开始
     * @param {type}
     * @return:
     * @Date: 2020-07-30 19:26:28
     */
    start() {
      this.isDisabled = this.$refs.uCode.canGetCode
    },
    /**
     * @author: yilingsj（315800015@qq.com）
     * @description: 倒计时结束
     * @param {type}
     * @return:
     * @Date: 2020-07-30 19:26:34
     */
    end() {
      this.isDisabled = this.$refs.uCode.canGetCode
    },
    /**
     * @author: yilingsj（315800015@qq.com）
     * @description: 监听验证码
     * @param {String} text 动态内容
     * @return:
     * @Date: 2020-07-30 19:26:44
     */
    codeChange(text) {
      this.changeText = text
    },
    /**
     * @author: yiling (315800015@qq.com)
     * @description: 公用点击事件
     * @param {Object} options 自定义参数
     * @return {*}
     * @Date: 2021-09-29 13:48:18
     */
    handleClickStop(options) {
      const { type } = options
      switch (type) {
        case 'login':
          if (!this.isagreement) {
            this.$toast('请勾选协议')
            return
          }
          this.isLogin = false
          setTimeout(() => {
            this.$refs.uForm.setRules(this.rules)
          }, 0)
          break
        case 'sendCode':
          this.handleStartCode()
          break
        default:
          break
      }
    },
    /**
     * @author: yilingsj（315800015@qq.com）
     * @description: 监听失去焦点
     * @param {Object} e event
     * @param {String} name string
     * @return {void}
     * @Date: 2020-07-08 10:38:37
     */
    handleBlur(e, name) {
      const { value } = e.detail
      const result = vailData[name](value)
      this[name + 'Verified'] = result === true
      if (result !== true) {
        this.$u.toast(result)
        return false
      }
      return true
    },
    /**
     * @author: yilingsj（315800015@qq.com）
     * @description: 获取验证码
     * @return {void}
     * @Date: 2020-07-08 10:38:20
     */
    handleStartCode() {
      this.mobileVerified = this.handleBlur({ detail: { value: this.form.username } }, 'mobile')
      console.log('mobileVerified=', this.mobileVerified)
      if (!this.mobileVerified) {
        return false
      }
      if (this.$refs.uCode.canGetCode) {
        const data = { telephone: this.form.username }
        this.$showLoading('发送中...')
        this.$u.debounce(() => {
          this.apiGetSendCode(data)
        }, 1000)
      }
    },
    /**
     * @author: yilingsj（315800015@qq.com）
     * @description: 发送短信
     * @param {Object} data 参数
     * @return {*}
     * @Date: 2021-06-30 21:35:37
     */
    apiGetSendCode(data) {
      this.$u.api.getAuthCode(data).then((res) => {
        uni.hideLoading()
        setTimeout(() => {
          this.isCode = true
          this.code_text = '重发验证码'
          this.$u.toast('验证码已发送')
        }, 0)
        this.$refs.uCode.start()
      })
    },
    /**
     * @author: yilingsj（315800015@qq.com）
     * @description: 注册提交前的校验
     * @param {*}
     * @return {*}
     * @Date: 2021-06-30 22:03:49
     */
    submitValidate() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          console.log('验证通过')
          this.$showLoading('登录中...')
          this.$u.debounce(() => {
            this.apiPostPhoneLogin()
          }, 1000)
        }
      })
    },
    /**
     * @author: yiling (315800015@qq.com)
     * @description: 请求登录接口
     * @param {*}
     * @return {*}
     * @Date: 2021-09-29 17:27:37
     */
    apiPostPhoneLogin() {
      const data = { ...this.form }
      this.$u.api
        .login(data)
        .then((res) => {
          // #ifdef APP-PLUS
          this.getLocations()
          // #endif
          uni.setStorageSync('mobile', this.form.username)
          this.$store.commit('user/setToken', res.data.token)
          this.$store.commit('user/setTokenHead', res.data.tokenHead)
          this.apiGetInfo()
		  this.hxLogin()
        })
        .finally(() => {
          uni.hideLoading()
        })
    },
	hxLogin(){
		// 这里登陆当前用户
		let mobile = uni.getStorageSync('mobile');
		const {user,pwd} = this.$WebIM.makeAuthMap(mobile)
		this.$WebIM.login(user, pwd).then(rep => {
			console.log("WebIM.conn.isOpened", this.$WebIM.conn.isOpened())
			console.log('login response', rep)
				this.$store.commit('hx/IS_LOGIN', rep)
		})
		
		console.log('App Show==========', Date.now())
	},
    apiGetInfo() {
      this.$u.api.info().then((res) => {
        const { data } = res
		uni.setStorageSync('memberId', data.id)
        if (data.gender==0) {
          uni.reLaunch({
            url: '/subPages/other/userGender',
          })
        } else {
          uni.reLaunch({
            url: '/pages/index/index',
          })
        }
      })
    },
    // 获取当前位置
    getLocations() {
      uni.getLocation({
        type: 'wgs84',
        geocode: true, // 设置该参数为true可直接获取经纬度及城市信息
        success: (res) => {
          var keys
          if (this.form.platform === 1) {
            keys = '42aefe76c04d2dd739a6e245109e908d'
          } else {
            keys = 'b5b025a1789258c621e85c46ee88cd94'
          }
          getAmapCode({
            key: keys,
            longitude: res.longitude,
            latitude: res.latitude,
            callback: (newRes) => {
              console.log(newRes, '地址解析数据')
              const address = newRes.data.regeocode.formatted_address
              console.log(address)
              if (address) {
                this.$u.api.saveLocation({ userLocation: address }).then((res) => {})
              }
            },
          })
        },
        fail: function () {
          console.log('获取地址信息失败')
        },
      })
    },
    // 获取当前位置
   getNowLocation() {
     var that = this;
   	try {
   		const geolocation = new BMap.Geolocation();
   		geolocation.getCurrentPosition(function(r) {
			uni.setStorageSync('latitude', r.latitude)
			uni.setStorageSync('longitude', r.longitude)
   			var city = r.address.city;
   			that.$u.api.PostUpdateInfo({
   				latitude:r.latitude,
   				longitude:r.longitude,
   				region: city,
   				province: r.address.province,
   				city: city,
   				detailLocation: r.address.street
   				
   			}).then((res) => {
   				console.log("获取到地址");
   				console.log(res);
   			})
   			
   			// that.apiGetFetchMemberList();
   			console.log(r.address.city);
   		});
   	} catch (e) {
   		console.log(e)
   	}
   },
  }, // 挂载一些方法
  onLoad(options) {
    // this.getSystemInfo()
	this.getNowLocation()
    console.log('onLoad', options, Date.now())
  }, // 生命周期回调—监听页面加载
  onShow() {}, // 生命周期回调—监听页面显示
  onReady() {}, // 生命周期回调—监听页面初次渲染完成
  onHide() {}, // 生命周期回调—监听页面隐藏
  onUnload() {}, // 生命周期回调—监听页面卸载
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100vh;
  background-size: cover;
  background-repeat: no-repeat;
}
.page1 {
  background-image: url('http://minio.tianhong.mobi/mall/xiaoq/login_bg.png');
}
.page2 {
  background-image: url('http://minio.tianhong.mobi/mall/xiaoq/home_bg.png');
}
.page-content {
  background: transparent;
  position: relative;
}
.box {
  position: absolute;
  width: 100%;
  padding: 0rpx 95rpx 0rpx !important;
  bottom: 66rpx;
  left: 0rpx;
}
.title {
  font-size: 63rpx;
  font-family: FZHei-B01S;
  font-weight: bold;
  color: #f6bf5d;
  line-height: 60rpx;
}
.subTitle {
  font-size: 25rpx;
  font-family: FZHei-B01S;
  font-weight: 400;
  color: #dcdcdc;
  line-height: 60rpx;
}

.wxLogin {
  width: 100%;
  padding: 160rpx 60rpx 0;
}
.mobile-form {
  &-item {
  }
  &-item_inner {
    padding: 0 0 0 51rpx;
    min-height: 90rpx;
    &.u-border::after {
      border-color: #ccc;
      border-radius: 20rpx; // 要*2
    }
  }
  &-item_input {
    flex: 1;
    padding-right: 10rpx;
    ::v-deep .u-input__input {
      font-size: 28rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      // color: rgba(96, 105, 114, 0.3);
      color: #fff;
    }
  }
  &-item_img {
    width: 44rpx;
    height: 44rpx;
    margin-right: 24rpx;
  }
  ::v-deep .u-form-item--left {
    display: none;
  }
  ::v-deep .u-form-item {
    padding: 18rpx 0;
  }
  &-item_code-button {
    font-size: 31rpx;
    height: 31rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    text-align: center;
    background-color: transparent;
    color: #000;
    margin: 0;
    border: none;
    padding: 0;
    margin: 0;
    // &.u-border::after {
    //   border-color: #fff;
    //   border-radius: 0;
    // }
  }
}
.code_box {
  margin-top: 150rpx;
}
.sendcode {
  font-size: 31rpx;
  font-family: Microsoft YaHei UI;
  font-weight: 400;
  color: #ffffff;
}
.code_text {
  width: 158rpx;
  height: 33rpx;
  font-size: 31rpx;
  font-family: Microsoft YaHei UI;
  font-weight: 400;
  text-decoration: underline;
  color: #ffffff;
  line-height: 1;
}
.text {
  font-size: 31rpx;
  font-family: Microsoft YaHei UI;
  font-weight: 400;
  color: #ffffff;
  line-height: 63rpx;
  text-align: center;
}
.btn {
  height: 90rpx;
  background: #ffffff;
  box-shadow: 0rpx 9rpx 43rpx 1rpx rgba(81, 90, 118, 0.33);
  border-radius: 45rpx;
  font-size: 42rpx;
  font-family: Microsoft YaHei UI;
  font-weight: 400;
  color: #000000;
  line-height: 90rpx;
}
.btn2 {
  width: 100%;
  margin: 506rpx 35rpx 0;
  height: 90rpx;
  background: #ffffff;
  border-radius: 45rpx;
  box-shadow: 0rpx 9rpx 43rpx 1rpx rgba(81, 90, 118, 0.33);
  font-size: 42rpx;
  font-family: Microsoft YaHei UI;
  font-weight: 400;
  color: #000000;
  line-height: 90rpx;
}
.agreement {
  font-size: 25rpx;
  font-family: Microsoft YaHei UI;
  font-weight: 400;
  color: #ffffff;
}
.agreement_text {
  color: #d7443e;
}
.icon {
  width: 32rpx;
  height: 32rpx;
}
</style>
